import config from '../data/curd.js'
import {
  _grid,
  _gridRows,
  _form,
  _append
} from '../ui/index.js'
import data from '../data/data.json'
import {
  _empty
} from '../ui/dom.js'
import {
  _random
} from '../math/index.js'

let fields = config.fields
let randomFields = fields.filter(t => t.type === 'random')
let indexField = fields.find(t => t.type === 'index')
let app = document.getElementById("app")
let data2 = Array.from({
  length: 3
}).map((t, i) => {
  let item = data[0]
  randomFields.forEach(t => {
    item[t.field] = _random.apply(Math, t.rang || [0, 10])
  })

  if (indexField) {
    item.index = i + 1
  }

  // Object.keys(item).forEach(field => {
  //   let fieldItem = fields.find(t => t.field === field)
  //   let type = fieldItem.type
  //   switch (type) {
  //     case "index":
  //       item[field] = i + 1
  //       break;
  //     case 'random':
  //       item[field] = _random.apply(Math, fieldItem.rang)
  //       break
  //   }

  // })
  return {
    ...item
  }
})

console.log(data2)

let form = _form(config, {
  add: (e, {
    model
  }) => {
    console.time('add')
    console.log(e.target, e.detail)
    let rows = []
    // for (let i = 0; i < model.number; i++) {
    rows.push(_gridRows(config.fields, model, data2.length))
    data2.push(model)

    // }
    _append(app.querySelector("table>tbody"), rows)
    console.timeEnd('add')
  },
  reset: () => {
    data2 = []
    _empty(app.querySelector("table>tbody"))
  },


})
_append(app, form)

let render = () => {
  console.time('render')
  let grid = _grid(config, data2, {
    del: (e, {
      model
    }) => {
      console.log(model)
      let {
        rowIndex
      } = model
      data2.splice(rowIndex, 1)
      // _empty(grid)
      // grid.querySelector
      // render()
    }
  })
  console.log(config, grid, data)
  // _empty(app)
  // _append(app, [form, grid])
  _append(app, grid)
  console.timeEnd('render')

}

render()